package com.wind.cloud.common.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.wind.cloud.common.config.rest.RestTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * mvc 配置
 *
 * @author wind.
 */
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.addAll(RestTemplateUtils.messageConverters());
        // 支持MediaType：*/*
        converters.add(new FastJsonHttpMessageConverter());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new WebRequestInterceptor());
        interceptorRegistration.addPathPatterns("/**");
    }

    @Autowired
    private MessageSource messageSource;

    @Override
    public Validator getValidator() {
        OptionalValidatorFactoryBean validator = new OptionalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource);
        return validator;
    }

}
